{qiniu} = require '../config'
request = require 'request'
jsdom = require 'jsdom'
jquery = require 'jquery'
async = require 'async'
weimedia = new qiniu.Bucket('weimedia')
db = require '../utils/connect'

Article = 
	approve: (id,done)->
		async.series [
				(cb)->
					sql = "update articles set state = 1 where id = ?"
					db.runSql sql, [id], cb
				(cb)->
					sql = "insert ignore into articles_approved select * from articles where id = ? "
					db.runSql sql, [id], cb
				(cb)->
					Article.complete id ,cb
			],done

	complete :(id,cb)->
		article = {}
		async.series [
				(callback)->
					sql = "select * from articles_approved where id = ?"
					db.queryOne sql, [id],(err, result)->
						article = result
						callback err
				(callback)->
					jsdom.env article.contenturl, (err, window)->
						$ = jquery.create window
						body = $('body').html()
						$('img').each (i,item)->
							src = $(item).attr('src')
							if src?.indexOf('http://mmsns.qpic.cn/mmsns/')>=0
								module.exports.getImg src, (err)->
									console.log err if err

						sql = "insert ignore into article_detail (id, content) values (?,?)"
						body = body.replace /http:\/\/mmsns.qpic.cn\/mmsns\/(.*?)(["'])/ig, ($1,$2,$3)->
							return 'http://weimedia.qiniudn.com/' + $2.replace('/','-')  + '.jpg' + $3
						db.runSql sql, [id,body], callback
				(callback)->
					module.exports.getImg article.cover, callback
			],cb

	getImg : (url, cb)->
		if url.indexOf('http://mmsns.qpic.cn/mmsns/')>=0
			name = url.replace('http://mmsns.qpic.cn/mmsns/','').replace('/','-') + '.jpg'
			exist = null
			async.series [
					(callback)->
						sql = "select * from imgs where name = ?"
						db.queryOne sql,[name],(err,result)->
							exist = result
							callback err
					(callback)->
						if exist
							assect =  weimedia.key name
							assect.stat (err, result)->
								if result?.error is 'no such file or directory'
									callback null
								else
									callback 'exist:' + name
						else
							callback null
					(callback)->
						ps = weimedia.createPutStream(url.replace('http://mmsns.qpic.cn/mmsns/','').replace('/','-') + '.jpg')
						ps.on 'error',(err)->
							console.log err
						ps.on 'end', (result)-> 
							callback null
						request.get(url).pipe ps
					(callback)->
						sql = "insert ignore into imgs (name) values (?)"
						db.runSql sql, [name], callback
				],(err)->
					console.log err if err
					cb null
		else 
			cb null

	convertImg : (url)->
		return 'http://weimedia.qiniudn.com/' + url.replace('http://mmsns.qpic.cn/mmsns/','').replace('/','-') + '.jpg'

module.exports = Article

# sql = "select cover from articles_approved"
# db.runSql sql, (err,result)->
# 	async.forEachSeries result,(article,cb)->
# 		module.exports.getImg article.cover, cb
